<template>
  <div>
    <van-cell icon="search" v-for="(item, index) in suggestions" :key="index" @click="$emit('search',item)">
      <div v-html="highlight(item)" slot="title"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js'
// import { debounce } from 'lodash'
function debounce (fn, num) {
  // 高阶函数
  // 闭包
  let timer = null
  return function (val) {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
    timer = setTimeout(() => {
      // 改变this的执行
      fn.call(this, val)
    }, num)
  }
}
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  filters: {
    highlight (text, searchText) {
      const reg = new RegExp(searchText, 'gi')
      return text.replace(reg, '<span style="color:red;">' + searchText + '</span>')
    }
  },
  components: {},
  data () {
    return {
      suggestions: [],
      testStr: 'hello<span style="color:red">world</span>'
    }
  },
  watch: {
    searchText: {
      handler: debounce(async function (val) {
        const { data: { data: { options } } } = await getSearchSuggestions(val)
        this.suggestions = options
      }, 1000),
      immediate: true
    }
  },
  created () {

  },
  methods: {
    highlight (text) {
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, '<span style="color:red;">' + this.searchText + '</span>')
    }
  }
}
</script>

<style lang="less" scoped>
</style>
